<?php

namespace app\api\model;

use app\api\model\Common;

class HotWord extends Common
{
    protected $func_trim;
    //自定义初始化
    protected function initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::initialize();
        //TODO:自定义的初始化
        $this->func_trim = function ($value) {
            return trim($value);
        };
    }
    protected $map = [
        'is_delete' => 0
    ];
    public function getFileList($limit, $page)
    {
        try {

            $result = $this->where($this->map)->field('id,title,describe,total,create_time,update_time')->limit($limit)->page($page)->order('id desc')->select();
            $total =  $this->where($this->map)->count();
            return [
                'list' => $result,
                'total' => $total,
                'total_page' => $limit != 0 ? ceil($total / $limit) : 0
            ];
        } catch (\Exception $e) {
            $this->error = '查询错误';
            return false;
        }
    }
    public function getFileDetail($id)
    {
        $this->map['id'] = $id;
        $_data = $this->get($this->map);
        if (!$_data) {
            $this->error = '暂无此数据';
            return false;
        }
        try {
            $_words_arr = json_decode($_data->content, true);
            $list = $this->groupByInitials($_words_arr);
            $data = [
                'hotword' => $list,
                'count' => $_data->total,
                'title' => $_data->title,
                'describe' => $_data->describe,
                'create_time' => $_data->create_time,
                'update_time' => $_data->update_time,
            ];
            return $data;
        } catch (\Exception $e) {
            $this->error = '查询错误';
            return false;
        }
    }

    /**
     * 按文件id添加热词
     */
    public function addFileWords($id, $words)
    {
        $this->map['id'] = $id;
        $_data = $this->get($this->map);
        if (!$_data) {
            $this->error = '暂无此数据';
            return false;
        }
        if($_data->status == 3){
            $this->error = '热词模型更新中';
            return false;
        }
        try {
            $_data->content = json_encode(array_unique(array_merge(json_decode($_data->content, true), array_unique(array_map($this->func_trim, array_filter(explode(",", trim($words))))))));
            $_data->total +=  count(explode(",", trim($words)));
            $_data->status = 2;
            $_data->save();
            return true;
        } catch (\Exception $e) {
            $this->error = '添加失败';
            return false;
        }
    }

    /**
     * 编辑文件中的热词
     */
    public function editFileWords($id, $words)
    {
        $this->map['id'] = $id;
        $_data = $this->get($this->map);
        if (!$_data) {
            $this->error = '暂无此数据';
            return false;
        }
        if($_data->status == 3){
            $this->error = '热词模型更新中';
            return false;
        }
        try {
            $_data->content = json_encode(array_map($this->func_trim, array_filter(explode(",", trim($words)))));
            $_data->total =  count(explode(",", trim($words)));
            $_data->status = 2;
            $_data->save();
            return true;
        } catch (\Exception $e) {
            $this->error = '更新失败';
            return false;
        }
    }

    /**
     * [updateDataById 编辑]
     * @linchuangbin
     * @DateTime  2017-02-10T21:24:49+0800
     * @param     [type]                   $param [description]
     * @param     [type]                   $id    [description]
     * @return    [type]                          [description]
     */
    public function updateDataById($param, $id, $validate = false)
    {
        $this->map['id'] = $id;
        $_data = $this->get($this->map);
        if (!$_data) {
            $this->error = '暂无此数据';
            return false;
        }

        // 验证
        if ($validate) {
            $validate = validate($this->name);
            if (!$validate->check($param)) {
                $this->error = $validate->getError();
                return false;
            }
        }

        try {
            $this->allowField(true)->save($param, [$this->getPk() => $id]);
            return true;
        } catch (\Exception $e) {
            $this->error = '编辑失败';
            return false;
        }
    }
    /**
     * 汉字数组转换为以字母分组的数组
     */
    public function groupByInitials($arr)
    {
        //前端非要这样
        $tmp = array('A'=>[],'B'=>[],'C'=>[],'D'=>[],'E'=>[],'F'=>[],'G'=>[],'H'=>[],'I'=>[],'J'=>[],'K'=>[],'L'=>[],'M'=>[],'N'=>[],'O'=>[],'P'=>[],'Q'=>[],'R'=>[],'S'=>[],'T'=>[],'U'=>[],'V'=>[],'W'=>[],'X'=>[],'Y'=>[],'Z'=>[],'#'=>[]);
        //$tmp = array();
        if (empty($arr)) {
            return $tmp;
        }
        $coll = collator_create('zh_CN');
        collator_sort($coll, $arr);

        foreach ($arr as $v) {
            $pinyin = transliterator_transliterate('Any-Latin; Latin-ASCII; Upper()', $v);
            //$tmp[substr($pinyin, 0, 1)][] = ['name' => $v];
            $tmp[(ord(substr($pinyin, 0, 1))>=65 && ord(substr($pinyin, 0, 1))<=90) ? substr($pinyin, 0, 1) : '#'][] = ['name' => $v];
        }
        return $tmp;
    }

    	/**
	 * [createData 新建]
	 * @linchuangbin
	 * @DateTime  2017-02-10T21:19:06+0800
	 * @param     array                    $param [description]
	 * @return    [array]                         [description]
	 */
	public function createData($param)
	{
		// 验证
		$validate = validate($this->name);
		if (!$validate->check($param)) {
			$this->error = $validate->getError();
			return false;
		}
		try {
			$this->data($param)->allowField(true)->save();
			return true;
		} catch(\Exception $e) {
            var_dump($e->getMessage());
			$this->error = "创建失败";
			return false;
		}
	}

}
